package com.yixun.qfbao.api.service.impl.wxmsg;

import com.alibaba.fastjson.JSONObject;
import com.yixun.qfbao.api.service.WeChatMessageService;
import com.yixun.qfbao.mapper.CompanyRelationMapper;
import com.yixun.qfbao.mapper.PartnerInfoMapper;
import com.yixun.qfbao.mapper.SubscriptionMapper;
import com.yixun.qfbao.mapper.WxBindMapper;
import com.yixun.qfbao.model.CompanyRelation;
import com.yixun.qfbao.model.Subscription;
import com.yixun.qfbao.model.WxBind;
import com.yixun.qfbao.model.dto.CompanyRelationDto;
import com.yixun.qfbao.model.dto.SubscriptionDto;
import com.yixun.qfbao.model.dto.WxBindDto;
import com.yixun.qfbao.model.enums.DelFlagEnum;
import com.yixun.qfbao.model.enums.SystemIdEnum;
import com.yixun.qfbao.util.WxReqestUtil;
import com.yixun.qfbao.xf.model.enums.AttetionStatusEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;

/**
 * 微信关注、取关处理类
 * @author zilong.liu
 *	TODO subscription信息，建议放入缓存中
 */
@Slf4j
@Service("msgSubscriptionService")
public class SubscriptionServiceImpl implements WeChatMessageService{

	@Autowired
	WxBindMapper wxBindMapper;
	@Autowired
	SubscriptionMapper subscriptionMapper;
	@Autowired
	PartnerInfoMapper partnerInfoMapper;
	@Autowired
	CompanyRelationMapper companyRelationMapper;
	@Autowired
	WxReqestUtil wxReqestUtil;
	/**
	 * 根据unionId，appId，openId，进行关注，取关设置。
	 * 根据openId，获取用户基本信息，然后对partner数据反改，以及更新tm_bind_info表
	 * 如果当前员工已经再系统存在，则关注、取关的时候均需要更新此时的人员状态
	 */
	@Override
	public void doBusiness(String appId, Map<String, String> msgMap, String companyUuid, String loginType) {
		String openId = msgMap.get("FromUserName");
		String event = msgMap.get("Event");
		log.info("SubscriptionServiceImpl->doBusiness->openId:{}", openId);
		log.info("SubscriptionServiceImpl->doBusiness->event:{}", event);
		String unionId = wxReqestUtil.getUnionId(openId, companyUuid, loginType, 0);
		// 先查询
		WxBindDto wxBindDto = new WxBindDto();
		wxBindDto.setAppId(appId);
		wxBindDto.setWxOpenId(openId);
		wxBindDto.setUnionId(unionId);
		wxBindDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
		//如果用户不关注，则需要通过openId进行查找，此时没有unionId
		if(!"subscribe".equals(event)) {
			wxBindDto.setWxOpenId(openId);
		}
		WxBind wxBind = wxBindMapper.selectByDto(wxBindDto);
		log.info("SubscriptionServiceImpl->doBusiness->appId:{}", appId);
		log.info("SubscriptionServiceImpl->doBusiness->unionId:{}", unionId);
		log.info("SubscriptionServiceImpl->doBusiness->wxBind:{}", wxBind);
		if("subscribe".equals(event)) {
			if(wxBind == null) {
				//如果没查找到，则新增
				WxBindDto insertWxBind = new WxBindDto();
				insertWxBind.setAppId(appId);
				insertWxBind.setAttentionStatus(AttetionStatusEnum.set_attetion.getNo().toString());
				insertWxBind.setUnionId(unionId);
				insertWxBind.setWxOpenId(openId);
				wxBindMapper.add(insertWxBind);
				editPartnerInfo(insertWxBind, AttetionStatusEnum.set_attetion.getNo().toString());
				return;
			}
			// 由当前信息，则更新为关注
			editBindInfo(wxBind , AttetionStatusEnum.set_attetion.getNo().toString());
		}else {
			if(wxBind == null) {
				return;
			}
			log.info("SubscriptionServiceImpl->doBusiness->wxBind:{}", wxBind.getId());
			editBindInfo(wxBind , AttetionStatusEnum.cancel_attetion.getNo().toString());
		}
	}
	
	private void editBindInfo(WxBind wxBind, String attetionStatus) {
		if(wxBind == null) {
			log.info("SubscriptionServiceImpl->doBusiness->wxBind=null");
			return;
		}
		log.info("SubscriptionServiceImpl->doBusiness->wxBind:{}", JSONObject.toJSONString(wxBind));
		editWxBind(wxBind, attetionStatus);
		editPartnerInfo(wxBind, attetionStatus);
	}
	
	/**
	 * 更新用户对应的信息，根据APPid以及unionId
	 */
	private void editPartnerInfo(WxBind wxBind, String attetionStatus) {
		String appId = wxBind.getAppId();
		String unionId = wxBind.getUnionId();
		String openId = wxBind.getWxOpenId();
		if(AttetionStatusEnum.cancel_attetion.getNo().toString().equals(attetionStatus)) {
			openId = "";
		}
		SubscriptionDto subscriptionDto = new SubscriptionDto();
		subscriptionDto.setAppId(appId);
		subscriptionDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
		List<Subscription> subsciptionList = subscriptionMapper.selectListByDto(subscriptionDto);
		log.info("SubscriptionServiceImpl->doBusiness->subsciptionList:{}", JSONObject.toJSONString(subsciptionList));
		if(CollectionUtils.isEmpty(subsciptionList)) {
			return;
		}
		
		// 除了总代对应的公司，还应该查询分销对应的公司
		CompanyRelationDto companyRelationDto = new CompanyRelationDto();
		List<Long> companyIds = new ArrayList<>();
		for (Subscription subscription : subsciptionList) {
			companyIds.add(subscription.getCompanyId());
		}
		companyRelationDto.setDevCompanyIds(companyIds);
		List<CompanyRelation> companyRelationList = companyRelationMapper.selectListByDto(companyRelationDto);
		if(!CollectionUtils.isEmpty(companyRelationList)) {
			for (CompanyRelation companyRelation : companyRelationList) {
				companyIds.add(companyRelation.getAgentCompany());
			}
		}
		Map<String, Object> params = new HashMap<>();
		params.put("wxOpenId", openId);
		params.put("unionId", unionId);
		params.put("companyIds", companyIds);
		params.put("lastLoginSystemId", SystemIdEnum.WEAPP_AGENCY.getCode());
		log.info("SubscriptionServiceImpl->doBusiness->params:{}", params);
		partnerInfoMapper.updateOpenIdByCompanyIdAndUnionId(params);
	}
	
	private void editWxBind(WxBind wxBind, String attetionStatus) {
		Long id = wxBind.getId();
		WxBind updateWxBind = new WxBind();
		updateWxBind.setId(id);
		updateWxBind.setAttentionStatus(attetionStatus);
		updateWxBind.setUpdateTime(new Date());
		wxBindMapper.edit(updateWxBind);
	}
	

}
